const WebSocket = require('ws');

const port = 4567;

const wss = new WebSocket.Server({ port: port });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('收到消息: %s', message);
    ws.send(JSON.stringify({ msg: `服务器已收到消息: ${message}` }));
  });
  // 循环发送消息给客户端
  setInterval(() => {
    const data = {
      cameraId: '213',
      uv: getRandomInt(1, 100),
    };
    ws.send(JSON.stringify(data));
  }, 10000);
});

console.log(`WebSocket 服务器正在监听端口 ${port}`);

// 计数器

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
